<?php

namespace Crm\Controller;
//require_once 'vendor/phpoffice/phpexcel/Classes/PHPExcel.php';
use Zend\Mvc\Controller\AbstractActionController;
use Faker\Factory;
use Crm\Common\UploaderHelper;
use Zend\Mvc\MvcEvent;

abstract class AbstractController extends AbstractActionController
{
    protected $site;
    protected $categoryTable;
    protected $orderTable;
    protected $orderitemTable;
    protected $organizationTable;
    protected $organizationAddrTable;
    protected $productTable;
    protected $productCategoryTable;
    protected $typeTable;
    protected $userTable;
    protected $userBalanceLogTable;
    protected $bannerTable;
    protected $cityTable;
    protected $catalogTable;
    protected $materialCatalog;
    protected $materialCategory;
    protected $material;
    protected $materialReportTable;
//    protected $properties=array();
    protected $crmUserTable;
    protected $voucherTable;
    protected $voucherTypeTable;
    protected $rechargeTable;
    protected $rechargeCardTable;
    protected $feedbackTable;
    protected $orderScoreTable;
    protected $userGroupTable;
    protected $powerManageTable;
    protected $powerGroupTable;
    protected $mealorderTable;

    protected $refundFeeLogTable;
    protected $returnOrderTable;
    protected $returnOrderitemTable;
    protected $adminOrgId;

    
//     function __call($function_name, $args)
//     {
//         try {
//             $tableName=str_replace('get','',$function_name);
//             $path=sprintf("Client\Table\%1s",$tableName);
//             return $this->getTable($this->properties[$tableName],$path);
//         } catch (\Exception $e) {
//             return parent::__call($function_name, $args);
//         }       
//     }
    
    protected function attachDefaultListeners()
    {
        parent::attachDefaultListeners();
        $events = $this->getEventManager();
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100);
    }
    
    public function preDispatch()
    {
        if(empty($_SESSION['account']['user_id'])){
            return $this->redirect()->toRoute('crm/login');
        }
        
        $this->adminOrgId = !empty($_SESSION['account']['org_id']) ? $_SESSION['account']['org_id'] : ''; 
    }
    
    /**
     * 获取配置参数
     * @return Config
     */
    protected function getConfigSys(){
        if(!$this->site){
    
            $config = $this->getServiceLocator()->get('Config');
            $this->site = $config['site'];
        }
        return $this->site;
    }
 
    protected function getMealorderTable()
    {
        return $this->getTable($this->mealorderTable,'Crm\Table\MealorderTable');
    }
    
    protected function getMaterialReportTable()
    {
        return $this->getTable($this->materialReportTable,'Crm\Table\MaterialReportTable');
    }
    
    protected function getMaterialTable()
    {
        return $this->getTable($this->material,'Crm\Table\MaterialTable');
    }
    
    protected function getMaterialCategoryTable()
    {
        return $this->getTable($this->materialCategory,'Crm\Table\MaterialCategoryTable');
    }
    
    protected function getMaterialCatalogTable()
    {
        return $this->getTable($this->materialCatalog,'Crm\Table\MaterialCatalogTable');
    }
    
    protected function getCityTable()
    {
        return $this->getTable($this->cityTable,'Crm\Table\CityTable');
    }
    
    protected function getCatalogTable()
    {
        return $this->getTable($this->catalogTable,'Crm\Table\CatalogTable');
    }
    
    protected function getCategoryTable()
    {
        return $this->getTable($this->categoryTable,'Crm\Table\CategoryTable');
    }
    
    protected function getOrderTable()
    {
        return $this->getTable($this->orderTable,'Crm\Table\OrderTable');
    }
    
    protected function getOrderitemTable()
    {
        return $this->getTable($this->orderitemTable,'Crm\Table\OrderitemTable');
    }
    
    protected function getOrganizationTable()
    {
        return $this->getTable($this->organizationTable,'Crm\Table\OrganizationTable');
    }
    
    protected function getOrganizationAddrTable()
    {
        return $this->getTable($this->organizationAddrTable,'Crm\Table\OrganizationAddrTable');
    }
    
    protected function getProductTable()
    {
        return $this->getTable($this->productTable,'Crm\Table\ProductTable');
    }
    
    protected function getProductCategoryTable()
    {
        return $this->getTable($this->productCategoryTable,'Crm\Table\ProductCategoryTable');
    }
    
    protected function getTypeTable()
    {
        return $this->getTable($this->typeTable,'Crm\Table\TypeTable');
    }
    
    protected function getUserTable()
    {
        return $this->getTable($this->userTable,'Crm\Table\UserTable');
    }
    
    protected function getUserBalanceLogTable()
    {
        return $this->getTable($this->userBalanceLogTable,'Crm\Table\UserBalanceLogTable');
    }
    
    protected function getBannerTable()
    {
        return $this->getTable($this->bannerTable,'Crm\Table\BannerTable');
    }
    protected function getCrmUserTable()
    {
        return $this->getTable($this->crmUserTable,'Crm\Table\CrmUserTable');
    }
    protected function getVoucherTable()
    {
        return $this->getTable($this->voucherTable,'Crm\Table\VoucherTable');
    }
    protected function getVoucherTypeTable()
    {
        return $this->getTable($this->voucherTypeTable,'Crm\Table\VoucherTypeTable');
    }
    protected function getRechargeTable()
    {
        return $this->getTable($this->rechargeTable,'Crm\Table\RechargeTable');
    }
    protected function getRechargeCardTable()
    {
        return $this->getTable($this->rechargeCardTable,'Crm\Table\RechargeCardTable');
    }
    protected function getFeedbackTable()
    {
        return $this->getTable($this->feedbackTable,'Crm\Table\FeedbackTable');
    }
    protected function getOrderScoreTable()
    {
        return $this->getTable($this->orderScoreTable,'Crm\Table\OrderScoreTable');
    }
    protected function getUserGroupTable()
    {
        return $this->getTable($this->userGroupTable,'Crm\Table\UserGroupTable');
    }
    protected function getPowerManageTable()
    {
        return $this->getTable($this->powerManageTable,'Crm\Table\PowerManageTable');
    }
    protected function getPowerGroupTable()
    {
        return $this->getTable($this->powerGroupTable,'Crm\Table\PowerGroupTable');
    }
    protected function getRefundFeeLogTable()
    {
        return $this->getTable($this->refundFeeLogTable,'Crm\Table\RefundFeeLogTable');
    }
    protected function getReturnOrderTable()
    {
        return $this->getTable($this->returnOrderTable,'Crm\Table\ReturnOrderTable');
    }
    protected function getReturnOrderitemTable()
    {
        return $this->getTable($this->returnOrderitemTable,'Crm\Table\ReturnOrderitemTable');
    }
        
    private function getTable($table,$table_name) {
        if (!$table) {
            $sm = $this->getServiceLocator();
            $table = $sm->get($table_name);
        }
        return $table;
    }

    /*
     * 循环执行函数
     */
    private function whileExe($times,$handler)
    {
        $result = 0;
        for($i=0;$i < $times;$i++){
            $result = $handler($i);
            if($result == 0) {
                return 0;
            }
        }
        return $result;
    }
    
    /*
     * 灌入虚拟数据
     */
    public function dumpFakeDataAction()
    {    
        $post = $this->request->getPost();
        $times = empty($post['times'])? 0:$post['times'];
        $result = $this->whileExe($times,$this->fakeData());
        if ($result == 1) {
            $response = array(
                'result' => true
            );
        } else {
            $response = array(
                'result' => false
            );
        }

        die(json_encode($response));
    }
    
    /*
     * 自定义需要灌入的虚拟数据
     */
    protected function fakeData()
    {
        return function() {
            $faker = Factory::create();
            $set = array(
                'user_id'=>$faker->randomNumber(7), //随机数字
                'org_id'=>$faker->randomNumber(3),
                'order_total_price'=>$faker->randomFloat(10,2,6), //随机价格
                'order_create_time'=>DATE_FORMAT($faker->dateTimeThisMonth($max = 'now'),'Y-m-d h:i:s') //随机日期
            );
            //return $this->getorderTable()->insert($set);
            return 1;
        };      
    }
    /**
     * 上传图片
     * @param unknown $fileName 控件名称
     */
    protected function uploadImg($fileName)
    {
        $uploaderHelper = new UploaderHelper($fileName,$this->getUploadConfig());
        $fileInfo = $uploaderHelper->getFileInfo();
        if($fileInfo['state']==='SUCCESS') $fileInfo['url'] = $fileInfo['url'];
        return $fileInfo;
    }
    protected function getUploadConfig()
    {
        $pathFormat = UploaderHelper::getPathFormat("/image/{yyyy}{mm}/{time}{rand:6}");
        $config = array(
            "pathFormat" => $pathFormat,
            "maxSize" => 2048000,
            "allowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
        );
        return $config;
    }
}